import 'dart:io';
import 'package:abc/controller/publish_post_controller.dart';
import 'package:abc/view/CustomAppBar.dart';
import 'package:abc/view/GradientButton.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:get/get_rx/src/rx_typedefs/rx_typedefs.dart';

class PublishPostPage extends GetView<PublishPostController> {
  const PublishPostPage({super.key});

  @override
  Widget build(BuildContext context) {
    if (!Get.isRegistered<PublishPostController>()) {
      Get.lazyPut(() => PublishPostController());
    }
    return Scaffold(
      backgroundColor: const Color(0xFF0E0F26), // 深色背景
      appBar: CustomAppBar(
        title: "发布帖子",
        onBack: () {
         controller. exitSure();
        },
      ),
      body: ListView(
        padding: const EdgeInsets.only(
          bottom: 20,
          left: 16,
          right: 16,
          top: 9,
        ),
        children: [
          // 1. 帖子类型、话题、价格设置区域
          _buildSettingSection(context),
          const SizedBox(height: 20),

          // 2. 标题和内容输入区域
          _buildTextInputs(),
          const SizedBox(height: 20),

          // 3. 图片上传区域
          _buildImageUpload(),
          const SizedBox(height: 20),

          //  4. 视频上传区域
          Obx(
            () => controller.selectedType.value == PostType.video
                ? _buildVideoUpload()
                : Container(),
          ),
          Obx(
            () => controller.selectedType.value == PostType.video
                ? SizedBox(height: 20)
                : Container(),
          ),

          GradientButton(
            text: '确认发布',
            margin: EdgeInsetsGeometry.all(0),
            onPressed: () {
              controller.publishPost();
            },
          ),
        ],
      ),
    );
  }

  // 帖子类型、话题、价格设置
  Widget _buildSettingSection(BuildContext context) {
    return Container(
      padding: const EdgeInsets.only(left: 10, right: 6, top: 10, bottom: 15),
      decoration: BoxDecoration(
        color: const Color(0x33959595),
        borderRadius: BorderRadius.circular(10),
      ),
      child: Column(
        children: [
          _buildTypeSelection(),
          const SizedBox(height: 15),
          Padding(
            padding: const EdgeInsets.symmetric(vertical: 10),
            child: Row(
              children: [
                Text(
                  '帖子话题',
                  style: const TextStyle(
                    color: Colors.white,
                    fontSize: 16,
                    fontWeight: FontWeight.w500,
                  ),
                ),
                const SizedBox(width: 40),
                Expanded(
                  child:Obx(() {
                    // 显示选中的话题或默认文本
                    final selectedTopics = controller.selectedTopics;
                    final displayText = selectedTopics.isEmpty 
                        ? '请关联话题' 
                        : selectedTopics.join(' ');
                    
                    return InkWell(
                      child: Text(
                        displayText,
                        style: TextStyle(
                          color: selectedTopics.isEmpty 
                              ? Color(0xFF999999) 
                              : Colors.white,
                          fontSize: 15,
                          fontWeight: FontWeight.w400,
                        ),
                      ),
                      onTap: () {
                        // 调用话题选择弹窗，可以传入外部话题列表
                        controller.showTopicSelectionBottomSheet(context);
                      },
                    );
                  }),
                ),
                Image.asset(
                  'assets/images/ic_arrow_right_gray.png',
                  width: 24,
                  height: 20,
                ),
                //
              ],
            ),
          ),

          Padding(
            padding: const EdgeInsets.only(top: 10),
            child: Row(
              children: [
                Text(
                  '价格设置',
                  style: const TextStyle(
                    color: Colors.white,
                    fontSize: 16,
                    fontWeight: FontWeight.w500,
                  ),
                ),
                const SizedBox(width: 40),
                Expanded(
                  child: _buildTextField(
                   keyboardType: TextInputType.numberWithOptions(decimal: true), // 允许数字和小数点
                    inputFormatters: [
                    FilteringTextInputFormatter.allow(RegExp(r'^\d+\.?\d{0,2}')), // 只允许数字和最多两位小数
                  ],
                   hintText:  '请填写金币，不填则默认免费',
                   maxLines: 1,
                   onValueChanged: (value) {
                     controller.prince.value = value;
                   }, 
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  // 帖子类型选择 (图文/视频)
  Widget _buildTypeSelection() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const Text(
          '帖子类型',
          style: TextStyle(
            color: Colors.white,
            fontSize: 16,
            fontWeight: FontWeight.w500,
          ),
        ),
        const SizedBox(height: 15),
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Row(
              children: [
                _buildTypeRadio('图文帖子', PostType.textImage, () {
                  controller.selectedType.value = PostType.textImage;
                }),
                const SizedBox(width: 40),
                _buildTypeRadio('视频帖子', PostType.video, () {
                  controller.selectedType.value = PostType.video;
                }),
              ],
            ),
          ],
        ),
      ],
    );
  }

  // 单个类型选择 Radio
  Widget _buildTypeRadio(String label, PostType type, Callback callback) {
    return GestureDetector(
      onTap: callback,
      child: Row(
        children: [
          Obx(
            () => Image.asset(
              controller.selectedType.value == type
                  ? 'assets/images/icon_selected.png'
                  : 'assets/images/icon_unselect.png',
              width: 20,
              height: 20,
            ),
          ),
          const SizedBox(width: 5),
          Text(
            label,
            style: const TextStyle(
              color: Colors.white,
              fontSize: 15,
              fontWeight: FontWeight.w400,
            ),
          ),
        ],
      ),
    );
  }

  // 标题和内容输入区域
  Widget _buildTextInputs() {
    return Container(
      padding: const EdgeInsets.all(10),
      decoration: BoxDecoration(
        color: const Color(0x33959595),
        borderRadius: BorderRadius.circular(10),
      ),

      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 标题输入
          const Text(
            '标题',
            style: TextStyle(
              color: Colors.white,
              fontSize: 16,
              fontWeight: FontWeight.w500,
            ),
          ).paddingOnly(bottom: 10),

          _buildTextField(hintText: '请填写帖子标题', maxLines: 1 ,onValueChanged: (value) {
                     controller.title.value = value;
                   }, ),
          const Text(
            '内容',
            style: TextStyle(
              color: Colors.white,
              fontSize: 16,
              fontWeight: FontWeight.w500,
            ),
          ).paddingSymmetric(vertical: 10),
          _buildTextField(hintText: '请输入帖子内容...', maxLines: 3, onValueChanged: (value) {
                     controller.content.value = value;
                   }, ),
        ],
      ),
    );
  }

  // 图片上传区域
  Widget _buildImageUpload() {
    return Container(
      padding: const EdgeInsets.only(left: 10, right: 10, top: 10, bottom: 15),
      decoration: BoxDecoration(
        color: const Color(0x33959595),
        borderRadius: BorderRadius.circular(10),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Text(
                '图片上传 ', //
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 16,
                  fontWeight: FontWeight.w500,
                ),
              ),
              Text(
                '(图片数量≤9, 大小≤1M)', //
                style: TextStyle(
                  color: Color(0xFF999999),
                  fontSize: 13,
                  fontWeight: FontWeight.w500,
                ),
              ),
            ],
          ),
          SizedBox(height: 10),
          Obx(
            () => GridView.builder(
              shrinkWrap: true,
              physics: const NeverScrollableScrollPhysics(),
              gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 3,
                crossAxisSpacing: 8,
                mainAxisSpacing: 8,
                childAspectRatio: 0.7,
              ),
              itemCount: controller.imagePaths.length < 9
                  ? controller.imagePaths.length + 1
                  : 9, // +1 是为了添加按钮
              itemBuilder: (context, index) {
                // 如果是最后一个item且图片数量小于9，显示添加按钮
                if (index == controller.imagePaths.length &&
                    controller.imagePaths.length < 9) {
                  return GestureDetector(
                    onTap: controller.selectImages,
                    child: Container(
                      alignment: Alignment.center,
                      decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.circular(10),
                      ),
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Image.asset(
                            'assets/images/ic_upload_image.png',
                            width: 39,
                            height: 39,
                          ),
                          SizedBox(height: 12),
                          Text(
                            '上传图片',
                            style: TextStyle(
                              color: Colors.black,
                              fontSize: 12,
                              fontWeight: FontWeight.w400,
                            ),
                          ),
                        ],
                      ),
                    ),
                  );
                } else if (index < controller.imagePaths.length) {
                  return Stack(
                    children: [
                      ClipRRect(
                        borderRadius: BorderRadius.circular(10),
                        child: Image.file(
                          File(controller.imagePaths[index]), // 使用File对象
                          fit: BoxFit.cover,
                          width: double.infinity,
                        ),
                      ),

                      // 删除按钮
                      Positioned(
                        right: 0,
                        top: 0,
                        child: GestureDetector(
                          onTap: () => controller.removeImage(index),
                          child: Image.asset(
                            'assets/images/ic_delete_img.png',
                            width: 24,
                            height: 23,
                          ),
                        ),
                      ),
                    ],
                  );
                } else {
                  return Container(color: Colors.red, height: 10);
                }
              },
            ),
          ),

          SizedBox(height: 10),
          // 默认公开图提示
          Text(
            '默认前两张图为公开图', //
            style: TextStyle(
              color: Color(0xFFF85046),
              fontSize: 13,
              fontWeight: FontWeight.w400,
            ),
          ),
        ],
      ),
    );
  }

  // 视频上传区域
  Widget _buildVideoUpload() {
    return Container(
      padding: const EdgeInsets.only(left: 10, right: 10, top: 10, bottom: 15),
      decoration: BoxDecoration(
        color: const Color(0x33959595),
        borderRadius: BorderRadius.circular(10),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Text(
                '视频上传 ', //
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 16,
                  fontWeight: FontWeight.w500,
                ),
              ),
              Text(
                '(大小≤600M)', //
                style: TextStyle(
                  color: Color(0xFF999999),
                  fontSize: 13,
                  fontWeight: FontWeight.w500,
                ),
              ),
            ],
          ),

          const SizedBox(height: 10),
          Row(
            children: [_buildVideoCover(), SizedBox(width: 10), _buildVideo()],
          ),
        ],
      ),
    );
  }

  Widget _buildVideoCover() {
    return Obx(
      () => Container(
        width: 105,
        height: 140,
        alignment: Alignment.center,
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(10),
        ),
        child: controller.videoImgCover.value != null
            ? Stack(
                children: [
                  ClipRRect(
                    borderRadius: BorderRadius.circular(10),
                    child: Image.file(
                      File(controller.videoImgCover.value!), // 使用File对象
                      fit: BoxFit.cover,
                      width: double.infinity,
                    ),
                  ),
                  // 删除按钮
                  Positioned(
                    right: 0,
                    top: 0,
                    child: GestureDetector(
                      onTap: () => controller.removeVideoImgCover(),
                      child: Image.asset(
                        'assets/images/ic_delete_img.png',
                        width: 24,
                        height: 23,
                      ),
                    ),
                  ),
                ],
              )
            : GestureDetector(
                onTap: () => controller.selectVideoCover(),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Image.asset(
                      'assets/images/ic_upload_image.png',
                      width: 39,
                      height: 39,
                    ),
                    SizedBox(height: 12),
                    Text(
                      '上传视频封面',
                      style: TextStyle(
                        color: Colors.black,
                        fontSize: 12,
                        fontWeight: FontWeight.w400,
                      ),
                    ),
                  ],
                ),
              ),
      ),
    );
  }

  Widget _buildVideo() {
    return Obx(
      () => Container(
        width: 105,
        height: 140,
        alignment: Alignment.center,
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(10),
        ),
        child: controller.thumbnailBytes.value != null
            ? Stack(
                children: [
                  // 点击视频缩略图播放视频
                  GestureDetector(
                    onTap: () => controller.playVideo(),
                    child: ClipRRect(
                      borderRadius: BorderRadius.circular(10),
                      child: Image.memory(
                        controller.thumbnailBytes.value!,
                        width: 105,
                        height: 140,
                        fit: BoxFit.cover,
                      ),
                    ),
                  ),
                  // // 播放按钮图标
                  // Positioned(
                  //   top: 0,
                  //   bottom: 0,
                  //   left: 0,
                  //   right: 0,
                  //   child: Center(
                  //     child: Container(
                  //       width: 30,
                  //       height: 30,
                  //       decoration: BoxDecoration(
                  //         color: Colors.black.withOpacity(0.5),
                  //         shape: BoxShape.circle,
                  //       ),
                  //       child: Icon(
                  //         Icons.play_arrow,
                  //         color: Colors.white,
                  //         size: 20,
                  //       ),
                  //     ),
                  //   ),
                  // ),
                  // 删除按钮
                  Positioned(
                    right: 0,
                    top: 0,
                    child: GestureDetector(
                      onTap: () => controller.removeVideo(),
                      child: Image.asset(
                        'assets/images/ic_delete_img.png',
                        width: 24,
                        height: 23,
                      ),
                    ),
                  ),
                ],
              )
            : GestureDetector(
                onTap: () => controller.selectVideo(),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Image.asset(
                      'assets/images/ic_upload_image.png',
                      width: 39,
                      height: 39,
                    ),
                    SizedBox(height: 12),
                    Text(
                      '上传视频',
                      style: TextStyle(
                        color: Colors.black,
                        fontSize: 12,
                        fontWeight: FontWeight.w400,
                      ),
                    ),
                  ],
                ),
              ),
      ),
    );
  }

  //final ValueChanged<String> onChanged;
  // --- 通用辅助 Widgets ---
  Widget _buildTextField({List<TextInputFormatter>? inputFormatters,TextInputType? keyboardType,required String hintText, required int maxLines,required ValueChanged onValueChanged }) {
    return SizedBox(
      child: TextFormField(
        maxLines: maxLines,
        keyboardType:keyboardType,
          inputFormatters:inputFormatters, // 设置输入格式化器
        style: const TextStyle(color: Colors.white),
        decoration: InputDecoration(
          hintText: hintText,
          hintStyle: const TextStyle(
            color: Color(0xFF999999),
            fontSize: 15.0,
            fontWeight: FontWeight.w400,
          ),

          border: InputBorder.none,
          
        ),
        onChanged: (value) {
          onValueChanged(value);
        },
      ),
      
    );
  }
}

